<template>
  <div class="dashboard-container">
    <!-- 第一行：业绩看板和两个图表水平放置 -->
    <el-row :gutter="20">
      <!-- 个人业绩看板 -->
      <el-col :span="8">
        <el-card class="performance-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>个人业绩</span>
              <el-radio-group v-model="performancePeriod" size="small" @change="handlePeriodChange">
                <el-radio-button label="today">今日</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="performance-grid">
            <div class="performance-item">
              <div class="performance-value">{{ performanceData.completedOrders }}</div>
              <div class="performance-label">已完成</div>
            </div>
            <div class="performance-item">
              <div class="performance-value">{{ performanceData.acceptedOrders }}</div>
              <div class="performance-label">已受理</div>
            </div>
            <div class="performance-item">
              <div class="performance-value">¥{{ (performanceData.totalIncome || 0).toFixed(2) }}</div>
              <div class="performance-label">服务总额</div>
            </div>
            <div class="performance-item">
              <div class="performance-value">
                <el-rate v-model="performanceData.averageRating" disabled show-score text-color="#ff9900" score-template="{value}" />
              </div>
              <div class="performance-label">平均评分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 任务状态分布 -->
      <el-col :span="8">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>任务状态分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="pieChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
      
      <!-- 最近7日工单完成量 -->
      <el-col :span="8">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近7日工单完成量</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="barChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 第二行：待办任务列表 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <!-- 待办任务 -->
        <el-card class="todo-task-card" shadow="hover" v-loading="loading">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <span class="task-title">待办任务</span>
                <el-tag type="primary" effect="dark" size="small">{{ acceptedTasks.length }}</el-tag>
              </div>
              <div class="header-actions">
                <el-button type="success" size="small" icon="Plus" @click="navigateToTaskHall">前往接单</el-button>
              </div>
            </div>
          </template>
          <el-table :data="acceptedTasks" style="width: 100%" height="400px" size="default">
            <el-table-column prop="expected_service_date" label="预约日期" width="120" sortable />
            <el-table-column prop="expected_time_slot" label="时间段" width="100" />
            <el-table-column prop="type" label="任务类型" width="100">
              <template #default="scope">
                <el-tag :type="getTaskTypeTag(scope.row.type)">{{ getTaskTypeName(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="special_requirements" label="特殊要求" show-overflow-tooltip width="100" />
            <el-table-column prop="contact_name" label="联系人" width="100" />
            <el-table-column prop="contact_phone" label="联系电话" width="120" />
            <el-table-column prop="address" label="服务地址" width="270" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="small">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级" width="80" align="center">
              <template #default="scope">
                <el-tag :type="getPriorityTag(scope.row.priority)" size="small">{{ scope.row.priority }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center" fixed="right">
              <template #default="scope">
                <el-button size="small" type="success" @click="handleComplete(scope.row)">
                  {{ getActionButtonText(scope.row.status) }}
                </el-button>
                <!-- <el-button size="small" type="primary" text @click="viewTaskDetail(scope.row)">查看</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <!-- 任务详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    :title="currentTask.type ? `${getTaskTypeName(currentTask.type)}任务详情` : '任务详情'"
    width="600px"
  >
    <el-descriptions :column="1" border>
      <el-descriptions-item label="任务编号">{{ currentTask.id }}</el-descriptions-item>
      <el-descriptions-item label="任务类型">
        <el-tag :type="getTaskTypeTag(currentTask.type)">{{ getTaskTypeName(currentTask.type) }}</el-tag>
      </el-descriptions-item>
      
      <!-- 保洁任务特有字段 -->
      <el-descriptions-item label="预约日期">{{ currentTask.expected_service_date }}</el-descriptions-item>
      <el-descriptions-item label="时间段">{{ currentTask.expected_time_slot }}</el-descriptions-item>
      <el-descriptions-item label="特殊要求">{{ currentTask.special_requirements || '标准保洁' }}</el-descriptions-item>
      <el-descriptions-item label="服务地址">{{ currentTask.address }}</el-descriptions-item>
      <el-descriptions-item label="联系人">{{ currentTask.contact_name || '无' }}</el-descriptions-item>
      <el-descriptions-item label="联系电话">{{ currentTask.contact_phone || '无' }}</el-descriptions-item>
      <el-descriptions-item label="申请时间">{{ currentTask.application_time }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="getStatusType(currentTask.status)">{{ currentTask.status }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item v-if="currentTask.completion_time" label="完成时间">{{ currentTask.completion_time }}</el-descriptions-item>
      <el-descriptions-item v-if="currentTask.rating" label="用户评分">
        <el-rate v-model="currentTask.rating" disabled/>
      </el-descriptions-item>
      <el-descriptions-item v-if="currentTask.review_content" label="评价内容">{{ currentTask.review_content }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElRate } from 'element-plus';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, PieChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components';
import VChart from 'vue-echarts';
import { dashboardService, cleaningService } from '@/api/tasks';
import { getTaskDetail } from '@/api/tasks';
import { createBill } from '@/api/finance';

// 注册 ECharts 组件
use([CanvasRenderer, BarChart, PieChart, GridComponent, TooltipComponent, TitleComponent, LegendComponent]);

export default {
  name: 'CleaningDashboard',
  components: {
    VChart,
    ElRate
  },
  setup() {
    const router = useRouter();
    const loading = ref(false);
    const performancePeriod = ref('today');

    // 数据存储
    const performanceData = reactive({
      completedOrders: 0,
      acceptedOrders: 0,
      totalIncome: 0,
      averageRating: 0,
    });
    
    // 任务列表
    const acceptedTasks = ref([]);
    const recentlyCompletedTasks = ref([]);
    
    // 详情对话框
    const detailDialogVisible = ref(false);
    const currentTask = ref({});
    
    // 加载业绩数据
    const loadPerformanceData = async (period) => {
      try {
        loading.value = true;
        const { data } = await dashboardService.getPerformanceStats(period);
        if (data.code === 200) {
          Object.assign(performanceData, data.data);
        }
      } catch (error) {
        console.error('加载业绩数据失败:', error);
        ElMessage.error('加载业绩数据失败');
      } finally {
        loading.value = false;
      }
    };

    // 加载待办任务
    const loadAcceptedTasks = async () => {
      try {
        loading.value = true;
        // 使用dashboardService.getTodoTasks获取当前登录用户的待办任务
        const response = await dashboardService.getTodoTasks();
        console.log('待办任务API响应:', response.data);
        
        if (response.data.code === 200) {
          // 过滤出类型为cleaning的任务
          const cleaningTasks = response.data.data.filter(task => task.type === 'cleaning');
          console.log('过滤后的保洁任务:', cleaningTasks);
          
          acceptedTasks.value = cleaningTasks.map(task => ({
            ...task,
            id: task.id,
            // 确保使用正确的字段名
            expected_service_date: task.expected_service_date || '未指定',
            expected_time_slot: task.expected_time_slot || '全天',
            special_requirements: task.special_requirements || '无',
            address: task.address || task.unit_info || '未指定',
            contact_name: task.contact_name || '未指定',
            contact_phone: task.contact_phone || '未指定',
            status: task.status
          }));
          
          console.log('处理后的保洁任务列表:', acceptedTasks.value);
        }
      } catch (error) {
        console.error('加载待办任务失败:', error);
        console.error('错误详情:', error.response?.data || error.message);
        ElMessage.error('加载待办任务失败');
      } finally {
        loading.value = false;
      }
    };

    // 加载已完成任务
    const loadCompletedTasks = async () => {
      try {
        loading.value = true;
        const { data } = await dashboardService.getCompletedTasks();
        if (data.code === 200) {
          recentlyCompletedTasks.value = data.data;
        }
      } catch (error) {
        console.error('加载已完成任务失败:', error);
        ElMessage.error('加载已完成任务失败');
      } finally {
        loading.value = false;
      }
    };

    // 加载任务状态分布
    const loadTaskDistribution = async () => {
      try {
        const { data } = await dashboardService.getTaskDistribution();
        if (data.code === 200) {
          pieChartData.value = data.data;
        }
      } catch (error) {
        console.error('加载任务状态分布失败:', error);
        ElMessage.error('加载任务状态分布失败');
      }
    };

    // 加载每周统计数据
    const loadWeeklyStats = async () => {
      try {
        const { data } = await dashboardService.getWeeklyCompletionStats();
        if (data.code === 200) {
          barChartLabels.value = data.data.labels;
          barChartValues.value = data.data.values;
        }
      } catch (error) {
        console.error('加载每周统计数据失败:', error);
        ElMessage.error('加载每周统计数据失败');
      }
    };

    // 图表数据
    const pieChartData = ref([]);
    const barChartLabels = ref([]);
    const barChartValues = ref([]);
    
    // 初始化图表
    onMounted(() => {
      loadAllData();
    });
    
    // 加载所有数据
    const loadAllData = () => {
      loadPerformanceData(performancePeriod.value);
      loadAcceptedTasks();
      loadCompletedTasks();
      loadTaskDistribution();
      loadWeeklyStats();
    };
    
    // 柱状图配置
    const barChartOption = computed(() => ({
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      grid: { left: '3%', right: '4%', bottom: '15%', top: '5%', containLabel: true },
      xAxis: { 
        type: 'category', 
        data: barChartLabels.value, 
        axisTick: { alignWithLabel: true } 
      },
      yAxis: { type: 'value' },
      series: [{ 
        name: '完成量', 
        type: 'bar', 
        barWidth: '60%', 
        data: barChartValues.value,
        itemStyle: {
          color: '#67C23A'
        }
      }]
    }));

    // 饼图配置
    const pieChartOption = computed(() => ({
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
        legend: { 
            top: '5%', 
            right: '2%', 
            orient: 'vertical',
            itemWidth: 10, 
            itemHeight: 10, 
            textStyle: {fontSize: 12},
            show: true
        },
        series: [{
            name: '任务状态',
            type: 'pie',
            center: ['40%', '55%'],
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
            label: { show: false },
            emphasis: { label: { show: true, fontSize: '16', fontWeight: 'bold' } },
            labelLine: { show: false },
            data: pieChartData.value
        }]
    }));

    // --- 逻辑方法 ---

    const getTaskTypeTag = (type) => {
      // 在保洁工作台中，类型总是 'cleaning'
      return 'success';
    };

    const getTaskTypeName = (type) => {
      // 在保洁工作台中，类型总是 '保洁'
      return '保洁';
    };

    // 根据任务状态获取操作按钮文本
    const getActionButtonText = (status) => {
      const buttonTextMap = {
        '待受理': '受理',
        '已受理': '开始服务',
        '服务中': '完成服务',
        '已完成': '查看',
        '已评价': '查看',
        '已取消': '查看'
      };
      return buttonTextMap[status] || '完成';
    };

    const getPriorityTag = (priority) => {
      const map = {
        '高': 'danger',
        '中': 'warning',
        '低': 'info'
      };
      return map[priority] || 'info';
    };

    // 获取状态标签类型
    const getStatusType = (status) => {
      const map = {
        '待受理': 'info',
        '已受理': 'warning',
        '服务中': 'warning',
        '已完成': 'success',
        '已评价': 'success',
        '已取消': 'danger'
      };
      return map[status] || '';
    };

    // 切换业绩周期
    const handlePeriodChange = (period) => {
        loadPerformanceData(period);
    };

    // 完成保洁任务
    const handleComplete = async (task) => {
      try {
        loading.value = true;
        let newStatus = '';
        
        // 检查任务状态，决定调用哪个服务
        if (task.status === '已受理') {
          newStatus = '服务中';
          await cleaningService.updateStatus(task.id, newStatus);
          ElMessage.success(`已开始服务: #${task.id}`);
        } else if (task.status === '服务中') {
          newStatus = '已完成';
          // 先更新状态
          const statusResponse = await cleaningService.updateStatus(task.id, newStatus);
          
          // 确保状态更新成功
          if (statusResponse.data.code === 200) {
            // 固定保洁服务费用为50元
            const amount = 50;
            
            try {
              const response = await createBill({
                service_id: task.id,
                service_type: 'cleaning',
                amount: amount
              });
              
              if (response.data.code === 200) {
                ElMessage.success(`服务已完成，并创建账单: #${response.data.data.bill_number}，服务费用: ¥${amount}`);
              } else {
                console.error('创建账单失败:', response.data);
                ElMessage.warning(`服务已完成，但账单创建失败: ${response.data.message}`);
              }
            } catch (billError) {
              console.error('创建账单失败:', billError);
              ElMessage.warning('服务已完成，但账单创建失败');
            }
          } else {
            ElMessage.error(`更新服务状态失败: ${statusResponse.data.message}`);
          }
        } else if (task.status === '待受理') {
          newStatus = '已受理';
          await cleaningService.updateStatus(task.id, newStatus);
          ElMessage.success(`已受理订单: #${task.id}`);
        } else {
          // 对于其他状态，可能只标记为完成
          newStatus = '已完成';
          await cleaningService.updateStatus(task.id, newStatus);
          ElMessage.success(`任务已完成: #${task.id}`);
        }
        
        // 重新加载待办任务列表，确保显示的是最新数据
        await loadAcceptedTasks();
        
        // 更新业绩数据和图表
        loadPerformanceData(performancePeriod.value);
        loadTaskDistribution();
        loadWeeklyStats();

      } catch (error) {
        console.error('操作任务失败:', error);
        ElMessage.error(`操作失败: ${error.message}`);
      } finally {
        loading.value = false;
      }
    };

    // 导航到接单大厅
    const navigateToTaskHall = () => {
      router.push('/staff/task-hall');
    };

    // 查看任务详情
    const viewTaskDetail = async (task) => {
      try {
        // 先使用当前任务数据显示，防止白屏
        currentTask.value = {...task};
        detailDialogVisible.value = true;
        
        // 调用API获取完整的任务详情
        const { data } = await getTaskDetail(task.id, task.type);
        
        if (data.code === 200) {
          // 更新详情数据
          currentTask.value = {
            ...currentTask.value,
            ...data.data
          };
        }
      } catch (error) {
        console.error('获取任务详情失败:', error);
      }
    };
    
    return {
      loading,
      performancePeriod,
      performanceData,
      acceptedTasks,
      recentlyCompletedTasks,
      barChartOption,
      pieChartOption,
      getStatusType,
      getTaskTypeTag,
      getTaskTypeName,
      getPriorityTag,
      getActionButtonText,
      handleComplete,
      handlePeriodChange,
      navigateToTaskHall,
      loadAllData,
      detailDialogVisible,
      currentTask,
      viewTaskDetail
    };
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
.task-title {
  font-weight: 600;
  font-size: 16px;
}
.performance-card {
  height: 270px;
}
.performance-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  padding: 10px 0;
}
.performance-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
}
.performance-value {
  font-size: 28px;
  font-weight: bold;
  color: #67C23A;
  line-height: 40px;
}
.performance-label {
  font-size: 14px;
  color: #4e5969;
  margin-top: 4px;
}
.todo-task-card {
  margin-bottom: 20px;
  height: 500px;
}
.chart-card {
  height: 270px;
}
.chart-container {
  height: 210px;
  width: 100%;
}
.chart {
  height: 100%;
  width: 100%;
}
</style> 